<template>
  <div id="content">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="contentSearch" class="demo-form-inline">
        <!-- 查询表单 -->
        <el-form-item>
          <el-input v-model="contentSearch.title" placeholder="广告名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="contentSearch.categoryId" placeholder="广告类型">
            <el-option label="所有类型" value="0"></el-option>
            <el-option :label="t.name" :value="t.id" v-for="t in categoryList" :key="t.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addContent">添加广告</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <!-- 广告列表表格 -->
      <el-table
          :data="contentList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="广告id"
            align="center"
            prop="id"/>
        <el-table-column
            label="广告名"
            prop="title"
            align="center"/>


        <el-table-column width="120px"
                         label="广告图">
          <template #default="scope">
            <el-image
                style="width: 90px; height: 90px"
                :src="scope.row.pic"
                :preview-src-list="[scope.row.pic]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="链接" prop="url">
          <template #default="scope">
            <!-- 渲染链接 -->
            <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
          </template>
        </el-table-column>
        <el-table-column
            label="类型"
            prop="cname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页控件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 编辑/新增广告对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{content}}
      <el-form :model="content" :rules="rules" ref="ruleForm">
        <el-form-item label="广告名" prop="title" :label-width="formLabelWidth">
          <el-input v-model="content.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="链接" prop="url" :label-width="formLabelWidth">
          <el-input v-model="content.url" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9001/files/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="content.pic" :src="content.pic" class="avatar" alt="广告图">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>

        <el-form-item label="所属类型" prop="categoryId" :label-width="formLabelWidth">
          <el-select v-model="content.categoryId" placeholder="请选择所属类型">
            <el-option label="所有类型" value="0"></el-option>
            <el-option :label="t.name" :value="t.id" v-for="t in categoryList" :key="t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveContent">保 存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import contentApi from "@/api/content"
import typeApi from "@/api/contentCategory"

export default {
  name: "ContentView",
  data() {
    // 自定义校验规则
    let checkId = (rule, value, callback) => {
      if (value === '' || value == null ) {
        return callback(new Error('类型不能为空'))
      }else if( value == 0){
        return callback(new Error('请选择类型'))
      } else{
        callback()
      }
    }


    return {
      contentList: [],
      page: 1,        // 当前面
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      contentSearch: {}, // 查询条件对象
      categoryList: [],   // 类型列表
      dialogFormVisible: false,  // 控制对话框显示
      content: {},       // 当前操作的广告对象
      title: '添加广告',  // 对话框标题
      formLabelWidth: '100px',  // 代表表单的标签宽度
      multipleSelection:[],     // 选中的多项广告
      ids: [],                 // 删除的广告编号列表
      // 校验规则
      rules: {
        title: [{ required: true, message: '请输入广告名', trigger: 'blur' }],
        url: [{ required: true, message: '请输入链接', trigger: 'blur' }],
        categoryId: [{ validator : checkId, trigger: 'blur' }]
      }
    }
  }
  ,
  created() {
    this.search()
    this.findAllCategory()
  },
  methods: {

    // 获取所有类型的信息
    async findAllCategory() {
      const {data: res} = await typeApi.findAllCategory()
      if (res.code === 200) {
        this.categoryList = res.data.list
      }
    },
    // 条件查询带分页，""可查出全部数据
    async search() {
      const {data: res} = await contentApi.search(this.page, this.pageSize, this.contentSearch)
      if (res.code === 200) {
        this.contentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    //添加广告
    addContent() {
      //跟修改框共用得改标题。
      this.title = "添加广告"
      this.content = {}
      this.dialogFormVisible = true
    },
    // 保存广告
    saveContent() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const url = this.content.id ? '/content/content/update' : '/content/content/add';
          const method = this.content.id ? 'put' : 'post';
          const {data:res} = await contentApi.save(url,method,this.content)
          console.log("res:",res)
          if (res.code === 200) {
            this.$message({ type: 'success', message: res.message });
            this.dialogFormVisible = false;
            this.search();
          } else {
            this.$message({ type: 'error', message: res.message });
          }

        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleAvatarSuccess(res) {

      this.content.pic = res.data.pic;
      console.log("图片链接：")
      console.log(this.content.pic)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    },
    // 修改广告
    handleEdit(index, row) {

      this.title = '修改广告'

      //修改需要信息回显
      this.content = row
      this.dialogFormVisible = true
    },
    handleDelete(index, row) {
      this.ids = row ? [row.id] : this.multipleSelection.map(m => m.id);
      this.$confirm(`确认删除编号为${this.ids}的广告吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        contentApi.delete(this.ids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>


.el-card {
  width: 100%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
